package dbb

import (
	"fyne.io/fyne/v2/container"
	_ "github.com/gogf/gf/contrib/drivers/sqlite/v2"
	"github.com/gogf/gf/v2/container/garray"
	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/os/gfile"
	"github.com/gogf/gf/v2/util/gconv"
	"github.com/y2h/fyne_poem/menu"
	"github.com/y2h/fyne_poem/util"
)

func connect() {
	pth, _ := Me.DbPath.Get()
	// println(pth)
	dbbase := gfile.Name(pth)
	// println(dbbase)
	if util.IsInSlice(dbbase, dbs.Keys()) {
		Me.Msg.SetText(dbbase + " already in the tree. please choose a new database.")
		return
	}

	Me.Db = dbs.GetOrSetFuncLock(dbbase, func() interface{} {
		db0, _ := gdb.New(gdb.ConfigNode{
			Type: "sqlite",
			Name: pth,
			Link: pth,
		})
		return db0

	}).(gdb.DB)

	Me.Ctx = Me.Db.GetCtx()
	Me.Name = dbbase
	// Me.Tbls, _ = Me.Db.Tables(Me.Ctx)
	tbls, _ := Me.Db.Tables(Ctx)
	// fmt.Println(tbls)
	Me.Tbls = garray.NewStrArrayFrom(tbls)
	RefreshDbtree()

	menu.Glog.Info(Me.Ctx, "tables of ", dbbase, " :", Me.Tbls)
	// db, _ = newDb.Master()

	SetKi(Me.Db, dbbase)
	CtnData = container.NewHBox()

	// ktbls := "Tables(" + gconv.String((Me.Tbls.Len())) + ")"
	// Me.Dbtree.OpenBranch(ktbls)

	Me.Dbtree.OpenAllBranches()
	// Me.Dbtree.Refresh()
}
func connect1(dbbase string) {
	Me.Ctx = Me.Db.GetCtx()
	Me.Name = dbbase
	// Me.Tbls, _ = Me.Db.Tables(Me.Ctx)

	tbls, _ := Me.Db.Tables(Ctx)
	Me.Tbls = garray.NewStrArrayFrom(tbls)
	RefreshDbtree()

	menu.Glog.Info(Me.Ctx, "tables of ", dbbase, " :", Me.Tbls)
	// db, _ = newDb.Master()

	SetKi(Me.Db, dbbase)

	ktbls := "Tables(" + gconv.String(Me.Tbls.Len()) + ")"

	// widgets.Treee.OpenAllBranches()
	Me.Dbtree.OpenBranch(ktbls)

	CtnData = container.NewHBox()
}
